package com.wct.jms;

import java.io.Serializable;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.jms.core.ProducerCallback;
import org.springframework.jms.core.SessionCallback;
import org.springframework.stereotype.Component;


public class Producer{

	private JmsTemplate jmsTemplate;
	private Destination destination;
	
	public JmsTemplate getJmsTemplate() {
		return jmsTemplate;
	}

	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}

	public Destination getDestination() {
		return destination;
	}

	public void setDestination(Destination destination) {
		this.destination = destination;
	}
	
	public void sendMessage(final Serializable obj) {
		//未使用MessageConverter的情况
		jmsTemplate.send(destination, new MessageCreator() {

			public Message createMessage(Session session) throws JMSException {
				ObjectMessage objMessage = session.createObjectMessage(obj);
				return objMessage;
			}
			
		});
//		//使用MessageConverter的情况
//		jmsTemplate.convertAndSend(destination, obj);
//		jmsTemplate.execute(new SessionCallback<Object>() {
//
//			public Object doInJms(Session session) throws JMSException {
//				MessageProducer producer = session.createProducer(destination);
//				Message message = session.createObjectMessage(obj);
//				producer.send(message);
//				return null;
//			}
//			
//		});
//		jmsTemplate.execute(new ProducerCallback<Object>() {
//
//			public Object doInJms(Session session, MessageProducer producer)
//					throws JMSException {
//				Message message = session.createObjectMessage(obj);
//				producer.send(destination, message);
//				return null;
//			}
//			
//		});
	}
	
}
